package megadrum.gui;

import megadrum.Common;
import javax.sound.midi.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MidiFirmwareUpdateDialog implements ActionListener, Receiver {

    private boolean ok = false;
    private JLabel label;
    private JButton proceed, cancel;
    private JDialog dialog;

    public MidiFirmwareUpdateDialog() {
    }

    public void send(MidiMessage event, long time) {
        //enable proceed button if we have received the confirmation byte
        if (event instanceof ShortMessage &&
                event.getStatus() == Common.CONFIRMATION_MIDI_MESSAGE[0] &&
                ((ShortMessage) event).getData1() == Common.CONFIRMATION_MIDI_MESSAGE[1] &&
                ((ShortMessage) event).getData2() == Common.CONFIRMATION_MIDI_MESSAGE[2]) {
            proceed.setEnabled(true);
        }
    }

    public void close() {
    }

    public boolean showDialog(JFrame f, String message, String title) {
        //Create everything
        label = new JLabel(message);
        proceed = new JButton("Proceed");
        proceed.addActionListener(this);
        proceed.setEnabled(false);
        cancel = new JButton("Cancel");
        cancel.addActionListener(this);

        //Lay out everything.
        JPanel pB1 = new JPanel();
        pB1.add(proceed);
        pB1.add(cancel);
        JPanel pB = new JPanel(new BorderLayout());
        pB.add(Box.createVerticalStrut(5), "North");
        pB.add(pB1, "Center");
        pB.add(Box.createVerticalStrut(5), "South");
        JPanel p = new JPanel(new BorderLayout());
        p.add(Box.createVerticalStrut(15), "North");
        p.add(label, "Center");
        p.add(pB, "South");
        p.add(Box.createHorizontalStrut(15), "West");
        p.add(Box.createHorizontalStrut(15), "East");
        dialog = new JDialog(f, title, true);
        dialog.getContentPane().add(p);
        dialog.setResizable(false);
        dialog.pack();
        dialog.setLocationRelativeTo(f);
        dialog.setVisible(true);
        return ok;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == proceed) {
            ok = true;
            dialog.dispose();
        } else if (e.getSource() == cancel) {
            ok = false;
            dialog.dispose();
        }
    }
}